<?php

namespace App\Http\Requests\School;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Spatie\Permission\Models\Role;

/**
 * Class StoreSchoolAdmin
 * @package App\Http\Requests\School
 * @author zjw
 * 新增学校管理员验证器
 */
class StoreSchoolAdmin extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'password' => 'required',
            'phone' => [
                'required',
                'regex:/^1[3|4|5|7|8|9][0-9]{9}$/',
                Rule::unique('school_admins')->where('status', 1)->where('school_id', \Auth::user()->school_id)
            ],
            'status' => 'required|integer',
            'roles' => [
                'array',
                function ($attribute, $value, $fail) {
                    foreach ($value as $role) {
                        if (Role::query()
                            ->where('guard_name','school')
                            ->where('school_id', \Auth::user()->school_id)
                            ->find($role)->doesntExist()) {
                            return $fail('未找到该权限角色');
                        }
                    }
                }
            ]
        ];
    }

    /**
     * @return array
     */
    public function attributes()
    {
        return [
            'name' => '用户名',
            'password' => '密码',
            'phone' => '电话号码',
            'status' => '状态',
            'roles' => '权限角色'
        ];
    }

    /**
     * @return array
     */
    public function messages()
    {
        return [
            'status.required' => '请填写:attribute',
            'status.integer' => ':attribute数据类型错误',
            'roles.array' => ':attribute数据类型错误',
            'name.required' => '请填写:attribute',
            'password.required' => '请填写:attribute',
            'phone.required' => '请填写:attribute',
            'phone.unique' => '已存在相同的:attribute',
            'phone.regex' => ':attribute格式错误',
        ];
    }
}
